<!--
 * @Author: tenet 18742176629@163.com
 * @Date: 2024/7/10 上午10:25
 * @LastEditors: tenet 18742176629@163.com
 * @LastEditTime: 2024/7/10 上午10:25
 * @FilePath: G:/chain-link-api-front-admin/src/views/system/banner\index.vue
 * @Description: 轮播图管理
-->
<template>

  <!-- 查询 -->
  <div class="queryBar">
    <div class="query_btns">
      <el-row :gutter="8">
        <el-col :span="1.5">
          <el-button type="primary" plain :icon="Plus" @click="handleClick('add')">{{ $t('button.Add') }}</el-button>
        </el-col>
      </el-row>
    </div>
  </div>

  <el-table :data="tableData" stripe border style="width: 100%; " size="large" v-loading="loading" max-height="600px">
    <el-table-column prop="id" :label="$t('banner.Id')" width="250" align="center" v-if="hiddenId"/>
    <el-table-column prop="skipUrl" :label="$t('banner.SkipUrl')" width="250" align="center"/>
    <el-table-column prop="pictureUrl" :label="$t('banner.BannerView')" width="auto" align="center">
      <template #default="scope">
        <el-image
            style="width: 100px; height: 100px"
            :src="`${mainUrl}${scope.row.pictureUrl}`"
            :preview-src-list="srcList"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            :initial-index="4"
            preview-teleported
            :hide-on-click-modal="true"
            @click="showView(scope)"
        />
      </template>
    </el-table-column>
    <el-table-column fixed="right" :label="$t('global.Operation')" width="150" align="center">
      <template #default="scope">
        <el-button link type="primary" size="small" @click="handleClick('update',scope)">{{ $t('global.Update') }}</el-button>
        <el-popconfirm :title="t('banner.DelImageTips')" @confirm="confirmSubmit(scope)">
          <template #reference>
            <el-button link type="danger" size="small">{{ $t('global.Delete') }}</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>

  <div class="page">
    <el-pagination v-model:current-page="pageIndex" :page-size="pageSize" layout="total, prev, pager, next"
                   :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
  </div>

  <!--  新增 | 修改 图片 dialog -->
  <el-dialog v-model="showDialog" :title="$t('banner.AddBanner')" width="500" center @close="resetForm">
    <el-form :model="form" :rules="rules" ref="ruleRef" label-width="auto" style="max-width: 600px">
      <el-form-item prop="file" :label="$t('banner.SelectImg')">
        <el-upload
            class="avatar-uploader"
            accept="image/*"
            :show-file-list="false"
            :headers="headers"
            :action="uploadUrl"
            :before-upload="beforeUpload"
            :on-success="handleSuccess"
        >
          <img v-if="form.pictureUrl" :src="`${mainUrl}${form.pictureUrl}`" class="avatar" alt=""/>
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item prop="skipUrl" :label="$t('banner.SkipUrl')">
        <el-input v-model.trim="form.skipUrl" type="text"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="resetForm"> {{ $t('global.Cancel') }}</el-button>
        <el-button type="primary" @click="submit" :loading="submitLoading">{{ $t('global.Submit') }}</el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup>
import {ref, onMounted, reactive, unref } from 'vue'
import { Plus } from "@element-plus/icons-vue";
import {ElMessage, ElPagination, ElTable} from "element-plus";
import { createPicture, getPictureList, deletePicture, updatePicture } from "@/require/api.js"
import {useI18n} from "vue-i18n";
import { useUserStore } from "@/stores";
const {t} = useI18n();
const userStore = useUserStore();

onMounted(() => {
  getList()
})

// 获取 token 上传文件需要请求头
const headers = {
  Authorization: userStore.getToken
}
// 去除mainUrl 字符串最后一位
const mainUrl = import.meta.env.VITE_BASE_URL.slice(0, -1)
const uploadUrl = import.meta.env.VITE_BASE_URL + 'api/upload'
console.log(uploadUrl)
const btnType = ref('')
const pageSize = ref(10)
const pageIndex = ref(1)
const total = ref(0)
const tableData = ref([])
const loading = ref(false) // 表格加载
const submitLoading = ref(false) // 提交按钮 loading
const showDialog = ref(false) // 新增图片dialog
const deleteDialog = ref(false) // 删除图片dialog
const ruleRef = ref(null)
const hiddenId = ref(false) // 隐藏id
const srcList = ref([]) // 图片预览

const originSkipUrl = ref()
const originPictureUrl = ref()

// 图片信息 form
const form = reactive({
  id:'',
  fileName:'',
  pictureUrl:'',
  skipUrl: '',
})

// 修改图片 editForm
const editForm = reactive({
  id:'',
  pictureUrl:'',
  skipUrl: '',
  fileName: '',
})

// 获取图片列表
async function getList() {
  try {
    loading.value = true
    const {code, data, msg} = await getPictureList({
      pageIndex: unref(pageIndex),
      pageSize: unref(pageSize),
    })
    if (code === 200) {
      tableData.value = data.list
      console.log('Fetched table data:', tableData.value); // 打印表格数据
      total.value = data.total
      // srcList.value = data.list.map(item => item.pictureUrl);
      console.log(tableData.value)
      console.log(`${mainUrl}`)
    } else {
      ElMessage.error(msg)
    }
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }
}



/***********************************      新增 | 修改图片 start     *********************************/
// 新增图片 dialog
async function handleClick(type, scope) {
  showDialog.value = true;
  btnType.value = type
  console.log(btnType.value)

  if( type === 'add'){
  }else if( type === 'update'){
    form.id = scope.row.id
    form.fileName = scope.row.fileName
    form.pictureUrl = scope.row.pictureUrl
    form.skipUrl = scope.row.skipUrl

    originSkipUrl.value = scope.row.skipUrl
    originPictureUrl.value = scope

    // editForm.id = scope.row.id
    // editForm.fileName = scope.row.fileName
    // editForm.pictureUrl = scope.row.pictureUrl
    // editForm.skipUrl = scope.row.skipUrl
  }
}

// 提交方法
async function submit(){
  console.log(btnType.value)
  if( btnType.value === 'add' ){
    // 新增 - 上传图片
    if (!form.file && !form.skipUrl) {
      ElMessage.warning(t('message.CheckForm'));
      return;
    }

    try {
      loading.value = true;
      const { code, data, msg } = await createPicture({
        pictureUrl: form.pictureUrl,
        skipUrl: form.skipUrl ,
        fileName: form.fileName ,
      });
      if (code === 200) {
        ElMessage.success(t('message.UploadSuccess'));
        console.log('Uploaded image URL:', data.pictureUrl); // 打印上传后的图片路径
        return data;
      } else {
        ElMessage.error(msg);
      }
    } catch (e) {
      console.log(e);
    } finally {
      await getList();
      loading.value = false;
      showDialog.value = false;
    }

  }else if( btnType.value === 'update' ){
    console.log(editForm.file, form.skipUrl, editForm.pictureUrl)
    // if (!editForm.pictureUrl && !form.skipUrl) {
    //   ElMessage.error(t('message.CheckForm'));
    //   return;
    // }

    try {
      loading.value = true;
      console.log(form.pictureUrl, editForm.pictureUrl)
      const { code, data, msg } = await updatePicture({
        skipUrl: form.skipUrl,
        id: form.id ,
        fileName: form.fileName ,
        pictureUrl: form.pictureUrl ,
      });
      if (code === 200) {
        ElMessage.success(t('message.UploadSuccess'));
        console.log('Updated image URL:', data.pictureUrl); // 打印更新后的图片路径
        return data;
      } else {
        ElMessage.error(msg);
      }
    } catch (e) {
      console.log(e);
    } finally {
      await getList();
      showDialog.value = false;
      loading.value = false;
    }
  }
}

/***********************************      新增 | 修改 图片 end     *********************************/


/***********************************      删除图片 start     *********************************/
// 提交删除
async function confirmSubmit(scope) {
  try{
    loading.value = true
    const { code, data, msg } = await deletePicture({
      id: scope.row.id,
      fileName: scope.row.fileName
    })
    if( code === 200 ){
      ElMessage.success(t('message.DelSuccess'))
    }else{
      ElMessage.error(msg)
    }
  } catch (e) {
    console.log(e)
  } finally {
    deleteDialog.value = false
    await getList()
    loading.value = false
  }
}
/***********************************      删除图片 end     *********************************/

// 点击预览图片
async function showView(scope){
  srcList.value[0] = `${mainUrl}${scope.row.pictureUrl}`
}
// 表单验证规则
const rules = reactive({
  skipUrl: [
    {required: true, message: t('message.SkipUrlIsNull'), trigger: 'blur'},
  ]
})

// 上传之前
async function beforeUpload(){
  submitLoading.value = true
}
// 上传成功
const handleSuccess = (file) => {
  submitLoading.value = false
  form.pictureUrl = file.data.url
  form.fileName = file.data.fileName
  console.log(form.pictureUrl)
}
// ************************** 上传图片 end **************************************

// 重置表单
function resetForm() {
  showDialog.value = false;
  form.id = '';
  form.skipUrl = '';
  form.fileName = ''
  form.pictureUrl = ''
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getList()
}

// 分页
const handleCurrentChange = (val) => {
  pageIndex.value = val
  getList()
}

</script>

<style scoped lang="less">

.avatar-uploader{
  border: 1px dashed #ededf2;
  transition: opacity 0.3s ease-in-out;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader:hover{
  border: 1px dashed #409eff;
  opacity: 0.7;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.queryBar {
  background-color: #fff;
  margin: .1rem 0;
  padding: .1rem 0;
  box-sizing: border-box;

  .query_btns {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
    margin: .15rem 0 0 0;
  }
}

// 图片样式
.demo-image__error .image-slot {
  font-size: 30px;
}

.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}

.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}

:deep(.el-upload-list){
  width: 200px;
}

</style>